import React, { PureComponent } from "react";
import { Card, Spin, Table } from "antd";
import dynamic from "umi/dynamic";
import { connect } from "dva";
import { getMenuRouter, getPageOperate } from "components/layouts/menuFn";
import PageLayout from "components/pageconlayout/PageLayout";
import { delay } from "utils/comm";
import styles from "./FlowList.less";
import { getBtnProps, getOprateDisable } from "./Tools/operationHelper";
import { emptyParams, initAppListData, initData } from "./Tools/serviceHelper";
import {
  getColumns,
  getPageProps,
  getRowSelectionProps,
  handlePageChange,
  renderStatus,
  getEllipsisCell,
} from "./Tools/tableHelper";
import SkipList from "@/pages/flowmonitor/components/flowlist/Tools/SkipList";
import ErrorList from "@/pages/flowmonitor/components/flowlist/Tools/ErrorList";

/*
const TableList = dynamic(async () => {
  await delay(1000);
  return import("../../components/tablelist/TableList");
});
*/
const QueryExtra = dynamic({ loader: async () => {
  await delay(500);
  return import("../QueryExtra");
} });
const AdvancedFilter = dynamic({ loader: async () => {
  await delay(800);
  return import("../AdvancedFilter");
} });
const Catalogue = dynamic({ loader: async () => {
  await delay(100);
  return import("components/catalogue/Catalogue");
} });
const DealForm = dynamic({ loader: async () => {
  await delay(100);
  return import("../DealForm");
} });

@connect(({ appListMenu, FlowMonitor, loading, Public }) => ({
  appListMenu,
  FlowMonitor,
  loading,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowHandle extends PureComponent {
  state = {
    filterVisible: false,
    visible: false,
    skipVisible:false,
    errorVisible:false,
    errorMessage: [],
    selectedKeys: [],
    selectedProcessKeys: [],
    selectedSkipProInsId:"",
    page: {
      pageNum: 1,
      pageSize: 10,
    },
  };

  getBtnProps = getBtnProps.bind(this, styles.btn, styles.disabled);

  getColumns = getColumns.bind(this);

  getEllipsisCell = getEllipsisCell.bind(this, styles.ellipsis);

  getMenuRouter = getMenuRouter.bind(this);

  getOprateDisable = getOprateDisable.bind(this);

  getPageOperate = getPageOperate.bind(this);

  getPageProps = getPageProps.bind(this);

  getRowSelectionProps = getRowSelectionProps.bind(this);

  handlePageChange = handlePageChange.bind(this);

  initAppListData = initAppListData.bind(this);

  initData = initData.bind(this);

  renderStatus = renderStatus.bind(this, styles.statusDot);

  searchParams = { ...emptyParams };

  selectedProcesses = [];

  componentDidMount() {
    this.initAppListData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FlowMonitor/clearData" });
  }

  getFormThis = (formThis, type = "advancedFilter") => {
    if (type === "advancedFilter") {
      this.filterForm = formThis;
    } else if (type === "queryExtra") {
      this.queryExtraForm = formThis;
    }
  };

  resetPageData = () => {
    const { dispatch } = this.props;
    this.searchParams = { ...emptyParams };
    dispatch({ type: "FlowMonitor/clearData" });
    this.setState({
      page: { pageNum: 1, pageSize: 10 },
      filterVisible: false,
    });
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    this.initAppListData();
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.searchParams, pageNum, pageSize };
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    if (this.filterForm) this.filterForm.handleSubmit();
    if (this.queryExtraForm) this.queryExtraForm.handleSubmit();
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  /* 我的流程单选择 */
  handleTypeSelect = (selectedKeys = [], e, preId, nomalSelectedKeys) => {
    const Keys = selectedKeys[0].split("|");

    const newSelectkeys = nomalSelectedKeys || selectedKeys;
    // console.log(e.node.props.isLeaf)
    if (!(selectedKeys && selectedKeys[0].length > 0)) return;
    if (e.node.props.isLeaf) {
      // 子节点
      this.searchParams = {
        ...this.searchParams,
        busiId: selectedKeys[0],
        appId: "",
        tenantId: "",
      };
    } else if (Keys[0] === "tenant") {
      this.searchParams = {
        ...this.searchParams,
        tenantId: Keys[Keys.length - 1],
        appId: "",
        busiId: "",
      };
    } else {
      this.searchParams = {
        ...this.searchParams,
        appId: Keys[Keys.length - 1],
        tenantId: "",
        busiId: "",
      };
    }
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    this.setState({ selectedKeys: newSelectkeys });
    this.handleSearch();
  };

  // 查询参数改变
  handleParamsChange = (newparams) => {
    this.searchParams = { ...this.searchParams, ...newparams };
  };

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  };

  handleDealFormVisible = (visible, record = "", title, action) => {
    this.record = record;
    // this.disable = false;
    this.title = title;
    this.action = action; // 操作
    this.setState({ visible });
    this.handleSearch();
  };

  handleDealSubmit = () => {
    this.selectedProcesses = [];
    this.setState({
      selectedProcessKeys: [],
    });
  };

  handleSkip = (visible, record) => {
    this.title = "自由跳转";
    this.setState({ skipVisible: visible , selectedSkipProInsId:record.processInstanceId});
  }

  handleSkipCancel = (visible) => {
    this.setState({ skipVisible: visible});
  }

  handleError = (visible, record) => {
    const errorMessage = record.errorMessage?.map(m => JSON.parse(m)) || [];
    this.setState({ errorVisible: visible, errorMessage});
  }

  handleErrorCancel = (visible) => {
    this.setState({ errorVisible: visible});
  }

  render() {
    const { loading, dispatch, appListMenu, FlowMonitor } = this.props;
    const {
      page: { pageNum, pageSize },
      filterVisible,
      visible,
      skipVisible,
      errorVisible,
      errorMessage,
      selectedSkipProInsId,
      selectedKeys,
      selectedProcessKeys,
    } = this.state;
    const {
      processData = [],
      totalCount = 0,
      // currentActivity, newActivity,
    } = FlowMonitor;
    const { appListMenuData = [] } = appListMenu;
    // const listLoading = loading.models.appListMenu;
    const modalLoading = loading.models.FlowMonitor;
    const processLoading = loading.effects["FlowMonitor/getProcessList"];
    const menuListLoading = loading.effects["appListMenu/getAppListData"];
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title="应用业务目录"
              style={{ width: "100%", height: "100%" }}
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104 - 10,
              }}
            >
              <Spin spinning={menuListLoading} delay={300}>
                <Catalogue
                  CatalogueData={appListMenuData}
                  treeNodeSelect={this.handleTypeSelect}
                  selectedKeys={selectedKeys}
                  // defaultSelectedKeys={[this.processType]}
                />
              </Spin>
            </Card>
          }
          rightContent={
            <Card
              className={styles.rightCon}
              title={
                <div className={styles.container}>
                  <span className={styles.title}>
                    流程列表(
                    {totalCount}
                    )
                  </span>
                  {this.getBtnProps(this.selectedProcesses).map((p) => (
                    <span {...p} />
                  ))}
                </div>
              }
              extra={
                <QueryExtra
                  handleParamsChange={this.handleParamsChange}
                  onSearch={this.handleSearch}
                  visible={filterVisible}
                  getFormThis={this.getFormThis}
                  handleFilterVisible={this.handleFilterVisible}
                />
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
              style={{ width: "100%" }}
            >
              <AdvancedFilter
                userTitle="发起人"
                dispatch={dispatch}
                onSearch={this.handleSearch}
                handleParamsChange={this.handleParamsChange}
                visible={filterVisible}
                getFormThis={this.getFormThis}
              />
              <Table
                className={styles.listcon}
                columns={this.getColumns()}
                dataSource={processData}
                loading={processLoading}
                rowKey="processInstanceId"
                rowSelection={this.getRowSelectionProps(selectedProcessKeys)}
                pagination={this.getPageProps(pageNum, pageSize, totalCount)}
              />
            </Card>
          }
        />
        {visible && (
          <DealForm
            title={this.title}
            action={this.action}
            visible={visible}
            handleCancel={this.handleDealFormVisible}
            handleDealSubmit={this.handleDealSubmit}
            dispatch={dispatch}
            // data={this.record || {}}
            // disable={this.disable}
            processInstanceIds={selectedProcessKeys}
            confirmLoading={modalLoading}
            // currentActivity={currentActivity}
            // newActivity={newActivity}
          />
        )}
        {skipVisible && (
          <SkipList
            visible={skipVisible}
            handleSkipCancel={this.handleSkipCancel}
            dispatch={dispatch}
            confirmLoading={modalLoading}
            processInstanceId={selectedSkipProInsId}
            initData={this.initData}
          />
        )}
        {errorVisible && (
          <ErrorList
            visible={errorVisible}
            handleErrorCancel={this.handleErrorCancel}
            errorMessage={errorMessage}
            initData={this.initData}
          />
        )
        }
      </div>
    );
  }
}

export default FlowHandle;
